package com.bugsnag.ohos;

import com.bugsnag.ohos.internal.ImmutableConfig;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;

/**
 * EventPayload
 *
 * @since 2021-07-01
 */
public class EventPayload implements JsonStream.Streamable {
    String apiKey;
    Event event;
    File eventFile;
    Notifier notifier;
    private ImmutableConfig config;

    /**
     * constructor
     *
     * @param apiKey
     * @param event
     * @param notifier
     * @param config
     */
    public EventPayload(String apiKey, Event event, Notifier notifier, ImmutableConfig config) {
        this(apiKey, event, null, notifier, config);
    }

    /**
     * constructor
     *
     * @param apiKey
     * @param event
     * @param eventFile
     * @param notifier
     * @param config
     */
    public EventPayload(String apiKey, Event event, File eventFile, Notifier notifier, ImmutableConfig config) {
        this.apiKey = apiKey;
        this.event = event;
        this.eventFile = eventFile;
        this.notifier = new Notifier(notifier.getName(), notifier.getVersion(), notifier.getUrl());
        this.notifier.setDependencies(notifier.getDependencies());
        this.config = config;
    }

    public Event getEvent() {
        return event;
    }

    public File getEventFile() {
        return eventFile;
    }

    Set<ErrorType> getErrorTypes() {
        if (event != null) {
            return event.getImpl().getErrorTypesFromStackframes();
        } else if (eventFile != null) {
            return EventFilenameInfo.fromFile(eventFile, config).errorTypes;
        } else {
            return Collections.emptySet();
        }
    }

    @Override
    public void toStream(JsonStream writer) throws IOException {
        writer.beginObject();
        writer.name("apiKey").value(apiKey);
        writer.name("payloadVersion").value("4.0");
        writer.name("notifier").value(notifier);
        writer.name("events").beginArray();
        if (event != null) {
            writer.value(event);
        } else if (eventFile != null) {
            writer.value(eventFile);
        }
        writer.endArray();
        writer.endObject();
    }
}
